package com.mflex.mwms.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.mflex.mwms.R;
import com.mflex.mwms.collector.ActivityCollector;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener, View.OnKeyListener {
    private ForceOfflinereceiver receiver;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ActivityCollector.addActivity(this);

        Intent intent = new Intent("com.example.logintestactivity.FORCE_OFFLINE");
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.mflex.mwms.activity.FORCE_OFFLINE");
        receiver = new ForceOfflinereceiver();
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    class ForceOfflinereceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            new MaterialDialog.Builder(context)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("Token过期，请重新登录")
                    .positiveText(R.string.lab_submit).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            ActivityCollector.finishAll();
                            Intent intent = new Intent(context, LoginActivity.class);
                            context.startActivity(intent);
                        }
                    })
                    .show();
        }
    }
}
